package com.jm.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jm.common.exception.YyghException;
import com.jm.common.helper.JwtHelper;
import com.jm.common.result.ResultCodeEnum;
import com.jm.enums.AuthStatusEnum;
import com.jm.model.user.Patient;
import com.jm.model.user.UserInfo;
import com.jm.user.mapper.UserInfoMapper;
import com.jm.user.service.UserInfoService;
import com.jm.vo.user.LoginVo;
import com.jm.vo.user.UserAuthVo;
import com.jm.vo.user.UserInfoQueryVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private PatientServiceImpl patientService;

    //用户登陆
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //校验参数
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        //校验验证码 容联云
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //微信登陆，绑定手机号码
        UserInfo userInfo = null;
        String openid = loginVo.getOpenid();
        if (!StringUtils.isEmpty(openid)) {//openid有值，绑定手机号
            userInfo = this.selectWxInfoOpenId(openid);
            if (userInfo != null) {
                userInfo.setPhone(phone);
                //更新数据库，添加手机号
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }

        //如果userInfo为空，进行正常手机登录
        if (userInfo == null) {
            //判断手机号是否第一次登录
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(queryWrapper);
            //第一次使用这个手机号,进行注册
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        //校验该用户是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        //返回数据 名称、token
        Map<String, Object> result = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {

            name = userInfo.getPhone();
        }
        result.put("name", name);
        //JWT生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        result.put("token", token);

        //返回
        return result;
    }

    //根据openid查看数据库是否存在当前用户
    @Override
    public UserInfo selectWxInfoOpenId(String openid) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo;
    }

    //用户认证
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        //认证人姓名
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    //用户列表（条件查询）
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        //userInfoQueryVo获取值
        Integer status = userInfoQueryVo.getStatus(); // 状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); // 认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); // 最早创建时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); // 最晚创建时间
        String name = userInfoQueryVo.getKeyword(); // 用户名称
        //对条件值进行非空判断
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        //调用mapper的方法
        IPage<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        userInfoPage.getRecords().stream().forEach(item->{
            this.packageUserInfo(item);
        });
        return userInfoPage;
    }

    //用户锁定
    @Override
    public void lock(Long userId, Integer status) {
        if(status==1||status==0){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    //用户详情
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map=new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllByUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    //认证审批
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus==2||authStatus==-1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        Integer authStatus = userInfo.getAuthStatus(); // 认证状态
        Integer status = userInfo.getStatus(); // 状态
        String authStatusString = AuthStatusEnum.getStatusNameByStatus(authStatus);
        userInfo.getParam().put("authStatusString",authStatusString);
        String statusString = status==0?"锁定":"正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
